package session

import (
	"sync"
	"time"
	"video/api/databases"
	"video/api/lib/utils"
)


var sessionMap  *sync.Map
func init()  {
	sessionMap = &sync.Map{}
}

func nowInMilli() int64{
	return time.Now().UnixNano()/1000000
}

func LoadSessionsFromDb()  {
	r, err := databases.RetrieveAllSessions()
	if err != nil {
		return
	}

	r.Range(func(k, v interface{}) bool{
		ss := v.(*databases.SimpleSession)
		sessionMap.Store(k, ss)
		return true
	})
}

func deleteExpiredSession(sid string) {
	sessionMap.Delete(sid)
	databases.DeleteSession(sid)
}

func GenerateNewSessionId(un string) string {
	id, _ := utils.NewUUID()
	ct := nowInMilli()
	ttl := ct + 30 * 60 * 1000// Severside session valid time: 30 min

	ss := &databases.SimpleSession{Username: un, TTL: ttl}
	sessionMap.Store(id, ss)
	databases.InsertSession(id, ttl, un)

	return id
}

func InSessionExpired(sid string) (string,bool)  {
	ss, ok := sessionMap.Load(sid)
	if ok {
		ct := nowInMilli()
		if ss.(*databases.SimpleSession).TTL < ct {
			deleteExpiredSession(sid)
			return "", true
		}

		return ss.(*databases.SimpleSession).Username, false
	}

	return "", true
}


